package session

import (
	"bytes"
	"crypto/md5"
	"encoding/base64"
	"encoding/binary"
	"errors"
	"math/rand"
	"time"
)

func buildAccountToken() string {
	var buffer bytes.Buffer
	binary.Write(&buffer, binary.BigEndian, time.Now().UnixNano())
	binary.Write(&buffer, binary.BigEndian, rand.Int63())
	data := md5.Sum(buffer.Bytes())
	return base64.StdEncoding.EncodeToString(data[:])
}

func buildAccountSession(accountID uint32) string {
	var buffer bytes.Buffer
	binary.Write(&buffer, binary.BigEndian, accountID)
	return base64.StdEncoding.EncodeToString(buffer.Bytes())
}

func parseAccountSession(session string) (accountID uint32, err error) {
	data, err := base64.StdEncoding.DecodeString(session)
	if len(data) < 4 || err != nil {
		err = errors.New("account session invalid.")
		return
	}
	var buffer = bytes.NewBuffer(data)
	binary.Read(buffer, binary.BigEndian, &accountID)
	return
}
